using System;
using System.Collections.Generic;

namespace SqlQueryBuilder.Queries
{
    /// <summary>
    /// Union Query
    /// </summary>
    public class UnionQuery : IInterrogationQuery
    {
        private readonly List<ISelectQuery> selectQueries;


        /// <summary>
        /// Initializes a new instance of the <see cref="UnionQuery"/> class.
        /// </summary>
        /// <param name="selectQueries">The select queries.</param>
        public UnionQuery(params ISelectQuery[] selectQueries)
        {
            this.selectQueries = new List<ISelectQuery>();
            foreach (var selectQuery in selectQueries)
            {
                this.selectQueries.Add(selectQuery);
            }
        }

        /// <summary>
        /// Builds the query.
        /// </summary>
        /// <returns></returns>
        public string BuildQuery()
        {
            bool isfirst = true;
            string UnionResult = string.Empty;

            if (selectQueries.Count < 2)
                throw new Exception("A Union query must contains at least two select queries");

            foreach (var query in selectQueries)
            {
                if(isfirst)
                    isfirst = false;
                else
                    UnionResult += " UNION ";

                UnionResult += string.Format("({0})",query.BuildQuery());
            }

            return UnionResult;
        }
    }
}